<template>
  <div v-if="loaded">
    <ProForm
      ref="formRef"
      :model="formState"
      :items="items"
      :disabled="readonly"
      :onValuesChange="onValuesChange"
      :formColLayout="formColLayout()"
      :requiredMark="!readonly"
      class="pro-form-modal"
      v-bind="formProps"
    >
    </ProForm>
    <Space class="footer-buttons mt-4">
      <slot></slot>
      <Button v-if="readonly" @click="onEdit()" v-hasPermission="'device:edit'"
        >编辑</Button
      >
      <template v-else>
        <Button type="primary" :loading="loading" @click="submit()">
          确认
        </Button>
        <Button @click="onCancel()">取消</Button>
      </template>
    </Space>
  </div>
</template>

<script setup lang="tsx">
import { computed, nextTick, ref, shallowRef, watch } from 'vue';
import { Button, Space, message } from 'ant-design-vue';
import { ProForm, ProFormProps } from '@/components/ProForm';
import { ItemProps } from '@/components/ProForm/interface';
import { LbsMap } from '@/components/map';
import { listToOption } from '@/utils/utils';
import { addDisableProperty2 } from '@/utils/utils';
import { getProjectData } from '@/api/config';
import { getModel, updateAllDevice } from '@/api/device';
import { fetchDictsOfType } from '@/api/dict';

defineOptions({
  name: 'Base',
});

interface Props {
  pageData: any;
  realTimeData?: any;
}
const props = defineProps<Props>();
const emit = defineEmits(['update:pageData', 'change']);
const loaded = ref(true);
const loading = ref(false);
const readonly = ref(true);
const formRef = shallowRef();
const formState = ref<Record<string, any>>({ ...props.pageData });
// const formState = computed<Record<string, any>>(() => {
//   return { ...props.pageData };
// });

watch(
  () => formState.value.installAddress,
  () => {
    formRef.value.setFiledValue(
      'installAddress',
      formState.value.installAddress,
    );
  },
);

const column = 3;
const formColLayout = () => {
  const num = 24 / column;
  return { xs: num, sm: num, md: num, lg: num };
};
const formProps = computed<ProFormProps>(() => {
  return {
    labelCol: { span: 6 },
    wrapperCol: { span: 20 },
  };
});
const onValuesChange = (
  values: Record<string, any>,
  state: Record<string, any>,
) => {
  // formState.value = {
  //   ...formState.value,
  //   ...state,
  // };
  emit('update:pageData', {
    ...formState.value,
    ...state,
  });
};
const refresh = () => {
  loaded.value = false;
  nextTick(() => {
    loaded.value = true;
  });
};
const itemObj = (
  label: string,
  type: any,
  field: string,
  required: boolean = false,
  props?: any,
  layout?: any,
  rules: any = [],
): ItemProps => {
  return {
    label,
    type,
    field,
    props: {
      placeholder: `请${type == 'input' ? '输入' : '选择'}${label}`,
      allowClear: false,
      ...props,
    },
    rules: [
      {
        required,
        message: `请${type == 'input' ? '输入' : '选择'}${label}`,
        trigger: 'blur',
      },
      ...rules,
    ],
    ...layout,
  };
};
const itemRender = (title: string): ItemProps => {
  return {
    label: { title },
    type: 'input',
    field: 'h5',
    formItemRender() {
      return <h5 class='h5'>{title}</h5>;
    },
  };
};

const sysDeviceModeOption = ref<Global.Option[]>([]);
const deviceIndustryOption = ref<Global.Option[]>([]);
const projectData = ref([]);
const modListOption = ref<Global.Option[]>([]);
const init = () => {
  fetchDictsOfType(['sys_device_mode', 'device_industry']).then((res: any) => {
    const { sys_device_mode, device_industry } = res.data;
    sysDeviceModeOption.value = listToOption(
      sys_device_mode,
      'dictLabel',
      'dictValue',
    );
    deviceIndustryOption.value = listToOption(
      device_industry,
      'dictLabel',
      'dictValue',
    );
  });
  getProjectData().then((res: any) => {
    projectData.value = addDisableProperty2(res.data);
  });
  getModel().then((res: any) => {
    modListOption.value = listToOption(res.data, 'model', 'modelId');
  });
};
init();
const processTreeData = (treeData: any) => {
  treeData.forEach((node: any) => {
    node.disabled = node.type == 1;
    if (node.children && node.children.length > 0) {
      processTreeData(node.children);
    }
  });
  return treeData;
};

const items = computed<ProFormProps['items']>(() => [
  itemRender('基础参数'),
  itemObj('设备序列号', 'input', 'code', false, {
    disabled: true,
  }),
  itemObj('设备类型', 'select', 'deviceType', false, {
    options: sysDeviceModeOption.value,
    disabled: true,
  }),
  itemObj('所属项目', 'treeSelect', 'projectId', true, {
    treeData: processTreeData(projectData.value),
    fieldNames: {
      value: 'id',
    },
  }),
  itemObj('设备型号', 'select', 'modelId', false, {
    options: modListOption.value,
    disabled: true,
  }),
  itemObj('软件版本', 'input', 'softwareVersion', false, {
    disabled: true,
  }),
  itemObj('固件版本', 'input', 'firmwareVersion', false, {
    disabled: true,
  }),
  itemRender('位置信息'),
  itemObj('经度', 'input', 'longitude', false, {
    disabled: true,
  }),
  itemObj('纬度', 'input', 'latitude', false, {
    disabled: true,
  }),
  itemObj('安装单位', 'input', 'installAddress', false, {
    disabled: true,
  }),
  itemObj('行业', 'select', 'deviceIndustry', false, {
    options: deviceIndustryOption.value,
  }),
  itemObj(
    '定位地址',
    'input',
    'address',
    false,
    {
      disabled: true,
    },
    {
      labelCol: { span: 3 },
      wrapperCol: { span: 21 },
      colProps: {
        span: 16,
      },
    },
  ),
  itemObj('', 'input', 'map', false, undefined, {
    customRender(formState: any) {
      return (
        <div class='h-96 map-container'>
          <LbsMap
            v-model:lat={formState['latitude']}
            v-model:lng={formState['longitude']}
            disabled={true}
          />
          <div v-show={readonly.value} class='map-mask h-96'></div>
        </div>
      );
    },
    wrapperCol: { span: 24 },
    colProps: {
      span: 24,
    },
  }),
]);
const onEdit = () => {
  readonly.value = false;
};
const onCancel = () => {
  formRef.value.clearValidate();
  formRef.value.resetFields();
  readonly.value = true;
};
const submit = async () => {
  try {
    const state = await formRef.value.validate();
    loading.value = true;
    await updateAllDevice(state);
    message.success('操作成功');
    formState.value = state;
    readonly.value = true;
    loading.value = false;
    emit('change');
    refresh();
  } catch (error) {
    console.error(error);
    loading.value = false;
  }
};
</script>

<style lang="scss">
.pro-form-modal {
  max-height: 59vh !important;
}
.map-container {
  position: relative;
  .map-mask {
    position: absolute;
    width: 100%;
    top: 0;
    left: 0;
  }
}
</style>
